<template>

    <div class="Main">
        <div class="MainTitle">
            分类列表
        </div>
        <div class="MianContent">
            <div style="margin-bottom: 20px;">
                <a-button type="primary" icon="plus" size="large" @click="AddCateList">新增一级分类</a-button>
            </div>
            <div>
                <a-tabs default-active-key="1" @change="callback">
                  <a-tab-pane key="1" tab="医械城"></a-tab-pane>
                  <a-tab-pane key="2" tab="药采购" force-render></a-tab-pane>
                  <a-tab-pane key="3" tab="中药馆"></a-tab-pane>
                  <!-- <a-tab-pane key="4" tab="普通商品"></a-tab-pane> -->
                </a-tabs>
                <a-table v-if="!loading" size="small" :columns="columns" :data-source="listData" defaultExpandAllRows class="components-table-demo-nested" :bordered="true" :pagination="false">
                    <div slot="Action" slot-scope="row,index">
                        <a-tag color="#108ee9" @click="ShowAndHidCate(index.id,index.status==1?0:1)">
                            {{index.status==0?'隐藏':'显示'}}
                        </a-tag>
                        <a-tag color="#87d068" @click="AddTwoCateList(index)">
                            新增
                        </a-tag>
                        <a-tag color="#2db7f5" @click="EditOneCateList(index)">
                            编辑
                        </a-tag>
                        <a-popconfirm placement="bottom" ok-text="删除" cancel-text="取消" @confirm="DeleteCateItem(index.id)">
                            <template slot="title">
                                <p>警告</p>
                                <p>确定删除该分类?</p>
                            </template>
                            <a-tag color="#f50">
                                删除
                            </a-tag>
                        </a-popconfirm>
                    </div>
                    <div slot="LOGO" slot-scope="row,index">
                        <img :src="row" style="width: 30px;height: 30px;" @click="ClickLookImage(row)">
                    </div>
                    <div slot="cateTitle" slot-scope="row,index">{{row + '（'+ index.id + '）'}}</div>
                    <a-table size="small" slot="expandedRowRender" slot-scope="row" :columns="innerColumns" :data-source="row.sub" :bordered="false" :pagination="false">
                        <div slot="Action" slot-scope="row,index">
                            <a-tag color="#108ee9" @click="ShowAndHidCate(index.id,index.status==1?0:1)">
                                {{index.status==0?'隐藏':'显示'}}
                            </a-tag>
                            <a-tag color="#2db7f5" @click="EditTwoCateList(index)">
                                编辑
                            </a-tag>
                            <a-popconfirm placement="bottom" ok-text="删除" cancel-text="取消" @confirm="DeleteCateItem(index.id)">
                                <template slot="title">
                                    <p>警告</p>
                                    <p>确定删除该分类?</p>
                                </template>
                                <a-tag color="#f50">
                                    删除
                                </a-tag>
                            </a-popconfirm>
                        </div>
                        <div slot="LOGO" slot-scope="row,index">
                            <img :src="row" style="width: 30px;height: 30px;" @click="ClickLookImage(row)">
                        </div>
                    </a-table>
                </a-table>
            </div>
        </div>
        <a-modal :title="ModalTitle" v-if="visible" v-model="visible" :width="620" :centered="true" :maskClosable="false" @ok="handleOk" @cancel="handleCancel">
            <div style="padding-left: 10px;">
                <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
                    <a-form-model-item label="上级分类" v-if="IsTwoCate">
                        <span style="color: #1890ff;font-size: 16px;">{{PidName}}</span>
                    </a-form-model-item>
                    <a-form-model-item ref="name" label="分类名称" prop="name">
                        <a-input v-model="form.name" @blur="() => {$refs.name.onFieldBlur();}" placeholder="请输入名称" allowClear />
                    </a-form-model-item>
                    <a-form-model-item ref="Order" label="排序" prop="Order">
                        <a-input v-model="form.Order" @blur="() => {$refs.Order.onFieldBlur();}" :min="0" type="number" allowClear placeholder="请输入优先级" />
                    </a-form-model-item>
                    <a-form-model-item label="是否隐藏" prop="Type">
                        <a-select v-model="form.Type" placeholder="请选择是否隐藏">
                            <a-select-option v-for="(item,index) in TypeList" :key="index" :value="item.value">
                                {{item.label}}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item ref="Order" label="分类类型" prop="typeCate">
                        <a-select v-model="form.typeCate" :disabled="TwoPid?true:false" @change="handleChange" placeholder="请选择分类类型">
                          <a-select-option value="1">
                            医械城
                          </a-select-option>
                          <a-select-option value="2">
                            药采购
                          </a-select-option>
                          <a-select-option value="3">
                            中药馆
                          </a-select-option>
                          <!-- <a-select-option value="4">
                            普通商品
                          </a-select-option> -->
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="ICON图" prop="imgs2">
                        <UploadImage v-model="form.imgs2" :maxNum="1"></UploadImage>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </a-modal>
        <a-modal v-model="LookImages" :footer="null" centered>
            <div style="margin: 10px;">
                <img :src="SelectImg" style="width: 100%;height: 100%;">
            </div>
        </a-modal>
    </div>
</template>

<script>
    import { USER_DATA } from '@/store/mutation-types';
    import { mapGetters, mapState, mapActions } from 'vuex';
    import { showErrors, showError, showSuccess } from '@/utils/showMsg';
    import UploadImage from '@/components/common/Upload';
    import { GetCateList, CateAdd, CateEdit, ChangeCateStatus, CateDelete } from '@/api/api.js';
    const columns = [
        { title: 'LOGO', dataIndex: 'logo', align: 'center', width: 100, scopedSlots: { customRender: 'LOGO' } },
        { title: '分类名', dataIndex: 'title', align: 'center', scopedSlots: { customRender: 'cateTitle' }, },
        { title: '操作', key: 'operation', scopedSlots: { customRender: 'Action' }, width: 250, align: 'center' },
    ];


    const innerColumns = [
        { title: 'LOGO', dataIndex: 'logo', align: 'center', width: 100, scopedSlots: { customRender: 'LOGO' } },
        { title: '二级分类名', dataIndex: 'title', align: 'center' },
        { title: '操作', key: 'operation', scopedSlots: { customRender: 'Action' }, width: 250, align: 'center' },
    ];
    export default {
        name: 'list',
        components: {
            UploadImage
        },
        data() {
            return {
                listData: [],
                columns,
                innerColumns,
                MarketId: this.$ls.get(USER_DATA).MarketId,
                visible: false,
                ModalTitle: '',
                labelCol: { span: 4 },
                wrapperCol: { span: 20 },
                form: {
                    name: '',
                    Type: 1,
                    Order: '',
                    imgs2: [], //图片
                    typeCate:null, //选择的分类类型
                },
                BannerListId: '',
                rules: {
                    name: [{ required: true, message: '请输入名称!', trigger: 'blur' }, { required: true, message: '请输入名称!', trigger: 'change' }, ],
                    typeCate: [{ required: true, message: '请选择分类类型!', trigger: 'blur' }],
                    // Order: [{ required: true, message: '请输入优先级!', trigger: 'blur' }, { required: true, message: '请输入优先级!', trigger: 'change' }, ],
                    imgs2: [{ type: 'array', required: true, message: '请上传封面图', trigger: 'change', }, ],
                },
                TypeList: [{
                    label: '显示',
                    value: 1
                }, {
                    label: '隐藏',
                    value: 0
                }, ],
                TwoPid: null, //父id
                selfId:'', //自身id
                IsTwoCate: false,
                PidName: '',
                loading: true,
                LookImages: false,
                SelectImg: '',
                tabsCurrent:1, //tabs选中项

            };
        },
        computed: {
            ...mapState({
                // listfields: state => state.account.fields,
            }),
        },

        created() {},
        mounted() {
            // this.GetAccountFields()
            this.GetList()
        },
        methods: {
            ...mapActions({
                // GetAccountFields: 'account/GetAccountFields',
            }),
            ClickLookImage(row) {
                this.SelectImg = row
                this.LookImages = true
            },
            // 切换tabs
            callback(e){
              const that = this;
              that.tabsCurrent = e;
              console.log(this.tabsCurrent);
              that.GetList()
            },
            // 选择弹窗分类
            handleChange(){
              console.log(this.typeCate);
            },
            // Modal弹框确定
            handleOk() {
                var that = this
                that.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        switch (that.ModalTitle) {
                            case '新增一级分类':
                                // 代码块
                                let params = {
                                    title: that.form.name, //分类名称
                                    logo: that.form.imgs2[0].url?that.form.imgs2[0].url:that.form.imgs2[0], //分类logo
                                    sort: that.form.Order, //排序
                                    pid: 0, //上级分类id ,顶级分类为0
                                    status: that.form.Type, //是否显示 0隐藏，1显示 默认1
                                    type:that.form.typeCate,
                                }
                                // console.log(params);
                                that.toCateAdd(params)
                                break;
                            case '新增二级分类':
                                // 代码块
                                let params1 = {
                                    title: that.form.name, //分类名称
                                    logo: that.form.imgs2[0].url?that.form.imgs2[0].url:that.form.imgs2[0], //分类logo
                                    sort: that.form.Order, //排序
                                    pid: that.TwoPid, //上级分类id ,顶级分类为0
                                    status: that.form.Type, //是否显示 0隐藏，1显示 默认1
                                    type:that.form.typeCate,
                                }
                                that.toCateAdd(params1)
                                break;
                            case '编辑一级分类':
                                // 代码块
                                let params2 = {
                                    id: that.selfId, //添加填0 修改分类id
                                    title: that.form.name, //分类名称
                                    logo: that.form.imgs2[0].url?that.form.imgs2[0].url:that.form.imgs2[0], //分类logo
                                    sort: that.form.Order, //排序
                                    pid: 0, //上级分类id ,顶级分类为0
                                    status: that.form.Type, //是否为热门分类 1是 0否 默认0
                                    type:that.form.typeCate,
                               }
                                that.cateUpdateApi(params2)
                                break;
                            case '编辑二级分类':
                                // 代码块
                                let params3 = {
                                    id: that.selfId, //添加填0 修改分类id
                                    title: that.form.name, //分类名称
                                    logo: that.form.imgs2[0].url?that.form.imgs2[0].url:that.form.imgs2[0], //分类logo
                                    sort: that.form.Order, //排序
                                    pid: that.TwoPid, //上级分类id ,顶级分类为0
                                    status: that.form.Type, //是否为热门分类 1是 0否 默认0
                                    type:that.form.typeCate,
                               }
                                that.cateUpdateApi(params3)
                                break;
                        }
                    } else {
                        return false;
                    }
                });
            },
            async DeleteCateItem(row) {
                var that = this
                let data = {
                    id: row, //添加填0 修改分类id
                }
                const res = await CateDelete(data)
                if (res.data.code == '1') {
                    // console.log(res);
                    showSuccess('操作成功');
                    that.GetList()
                } else {
                    showError(res.data.msg)
                }
            },
            EditOneCateList(row) {
                var that = this
                console.log(row);
                that.selfId = row.id
                that.TwoPid = row.id
                that.ModalTitle = '编辑一级分类'
                that.form.name = row.title
                that.form.Type = row.status
                that.form.Order = row.sort
                that.form.typeCate = row.type.toString()
                that.form.imgs2 = row.logo?[{ url: row.logo}]:[];
                that.visible = true
            },
            EditTwoCateList(row) {
                var that = this
                console.log(row);

                that.selfId = row.id
                that.TwoPid = row.pid
                that.ModalTitle = '编辑二级分类'
                that.form.name = row.title
                that.form.Type = row.status
                that.form.Order = row.sort
                that.form.typeCate = row.type.toString()
                that.form.imgs2 = row.logo?[{ url: row.logo}]:[];
                that.visible = true
            },
            AddTwoCateList(row) {
                var that = this
                console.log(row);
                that.TwoPid = row.id
                that.IsTwoCate = true
                that.PidName = row.title
                that.form.typeCate = row.type.toString()
                that.ModalTitle = '新增二级分类'
                that.visible = true
            },
            // Modal弹框取消
            handleCancel() {
                var that = this
                that.$refs.ruleForm.resetFields();
                that.TwoCateId = ''
                that.IsTwoCate = false
                that.PidName = ''
                that.TwoPid = null
                that.form.typeCate = null
                that.form.name = ''
                that.form.Order = ''
                that.form.imgs2 = []
                that.visible = false
            },
            AddCateList() {
                var that = this
                that.ModalTitle = '新增一级分类'
                that.visible = true
            },
            async ShowAndHidCate(id, show) {
                var that = this
                let data = {
                    id: id, //添加填0 修改分类id
                    status: show, //分类名称
                }
                const res = await ChangeCateStatus(data)
                if (res.data.code == '1') {
                    // console.log(res);
                    showSuccess('操作成功');
                    that.GetList()
                } else {
                    showError(res.data.msg)
                }
            },
            // 新增分类
            async toCateAdd(params){
              let that= this;
              let data = {
                pid:params.pid,
                logo:params.logo,
                title:params.title,
                sort:params.sort,
                status:params.status,
                type:params.type
              }
              let res = await CateAdd(data)
              if (res.data.code == '1') {
                    // console.log(res);
                    showSuccess('新增成功');
                    setTimeout(() => {
                        that.handleCancel()
                        that.GetList()
                    }, 500)
                } else {
                    showError(res.data.msg)
                }
            },

            // 编辑分类
            async cateUpdateApi(params) {
                var that = this
                let data = {
                    id:params.id, //分类ID
                    pid:params.pid, //分类父ID(顶级分类为0)
                    logo:params.logo, //分类图标
                    title:params.title, //分类名称
                    sort:params.sort, //分类排序
                    status:params.status, //状态(0隐藏,1显示)
                    type:params.type
                }
                const res = await CateEdit(data)
                if (res.data.code == '1') {
                    // console.log(res);
                    showSuccess('操作成功');
                    setTimeout(() => {
                        that.handleCancel()
                        that.GetList()
                    }, 500)
                } else {
                    showError(res.data.msg)
                }
            },
            // 获取数据列表API
            async GetList() {
                var that = this
                let data = {
                    type: that.tabsCurrent,
                }
                const res = await GetCateList(data)
                if (res.data.code == '1') {
                    const data = res.data.data
                    // console.log(data);
                    if (data.length > 0) {
                        data.forEach((item, index) => {
                            item.key = item.id
                            if (item.sub) {
                                item.sub.forEach((items, indexs) => {
                                    items.key = items.id
                                })
                            }
                        })
                    }
                    that.listData = data ? data : []
                    that.loading = false
                } else {
                    showError(res.data.msg)
                }
            },
        },
    };
</script>

<style scoped lang="stylus">
    .editable-row-operations a {
        margin-right: 12px;
    }

    .Main {
        border-radius: 10px;
        overflow: hidden;
        background: #fff;

        .MainTitle {
            font-size: 24px;
            color: #333;
            margin: 10px 20px;
            position: relative;
        }

        .MainTitle:before {
            content: '';
            width: 40px;
            height: 12px;
            background: linear-gradient(270deg, rgba(0, 158, 238, 0) 0%, rgba(0, 158, 238, 0.3) 100%);
            position: absolute;
            bottom: 2px;
            left: 0;
        }

        .MianContent {
            padding: 10px 20px 20px 20px;


            .MainTopAction {
                margin-bottom: 20px;
                display: flex;
                align-items: center;
                flex-wrap: wrap;

                .MainTopActionView {
                    display: flex;
                    align-items: center;
                    flex-wrap: wrap;

                    .MainTopActionOne {
                        margin-right: 30px;

                        span {
                            margin-right: 20px;
                        }
                    }

                    .MainTopActionTwo {
                        span {
                            margin-right: 20px;
                        }
                    }
                }

                .MainTopActionThree {
                    display: flex;
                    align-items: center;
                    margin-left: 20px;
                }
            }
        }
    }
</style>